<template>
	<div class="activity-5x6">
		<base-nav-bar :title="title" v-if="title" isGoback />
		<div class="max-w-[720px] mx-auto">
			<div class="activity-5x6__body">
				<base-image
					v-if="activityInfo?.isImage && image"
					class="activity-5x6__img w-full"
					:src="image" />
				<base-loading v-if="loading" status="loading" />
				<div
					v-else-if="content"
					class="activity-5x6__content rich-text-area ck-content"
					v-html="content" />
				<base-loading v-else status="empty" />
			</div>
			<div v-if="activityInfo?.isCta && cta" class="activity-5x6__footer">
				<base-button type="primary" round block @click="jumpRouteUrl(activityInfo?.ctaLink)">
					{{ cta }}
				</base-button>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router'
import { getMultiText } from '@/api/assistants'
import { ref, computed, watch } from 'vue'
import { fmtAmount, jumpRouteUrl } from '@/utils'
import { AccountRegion } from '@/enums'
import { IMAGE_URL } from '@/constants'
import { BaseButton, BaseLoading, BaseNavBar, BaseImage } from '@/components/base'
import { useAppStore } from '@/store'

// const store = useStore()
const route = useRoute()
const appStore = useAppStore()

const loading = ref(false)
const activityInfo: any = ref(null)

const title = computed(() => activityInfo.value?.title[appStore.lang])

const image = computed(() =>
	activityInfo.value?.image?.[appStore.lang]
		? IMAGE_URL + activityInfo.value?.image[appStore.lang]
		: ''
)

const cta = computed(() => activityInfo.value?.cta[appStore.lang])

const content = computed(() => {
	if (activityInfo.value) {
		return formatToMobile(activityInfo.value.content[appStore.lang], activityInfo.value.regionData)
	}
	return ''
})

/**
 * 插值数据类型
 * @type {Object.<string,{id: string, name: string, type: string}>}
 */
const RegionFormatType = {
	amount: { id: 'amount', name: '金额', type: 'string' },
	amountUSD: { id: 'amountUSD', name: '金额USD', type: 'string' },
	number: { id: 'number', name: '数字', type: 'string' },
	percentage: { id: 'percentage', name: '百分比', type: 'string' },
	expression: { id: 'expression', name: '显示/隐藏', type: 'boolean' }
}

const formatFn = {
	[RegionFormatType.amount.id]: fmtAmount,
	[RegionFormatType.amountUSD.id]: fmtAmount,
	[RegionFormatType.expression.id]: (value: any) => value,
	[RegionFormatType.number.id]: (value: any) => value,
	[RegionFormatType.percentage.id]: (value: any) => value * 100 + '%'
}

// 格式化到手机端展示
const formatToMobile = (text: any, regionData: any) => {
	if (!text) {
		return ''
	}
	const currency = appStore.currency
	// 匹配 ⩽tag⩾内容⩽/tag⩾ 包裹的字段，提取标签名和内容
	const regx = /⩽(.*?)⩾(.*?)⩽\/\1⩾/g
	// 匹配 {} 包裹的字段，然后提取字段内部的内容
	const regx2 = /\{([^{}]+)\}/g
	const replaceFn = (match: any, tagName: any, content: any) => {
		const item = regionData[String(tagName).trim()]
		if (!item) {
			console.warn(`未知插值字段: "${tagName}"; 不存在于 regionData`)
			// 未知字段，保持原样
			return match
		}
		const format = formatFn[item.type]
		if (typeof format !== 'function') {
			console.warn(`匹配TagName: "${tagName}" 的格式化方法不存在! 或不是函数类型: ${typeof format}`)
			// 未知字段，保持原样
			return match
		}
		if (item.type === RegionFormatType.expression.id) {
			return item[currency] ? format(content) : ''
		}
		return format(item[currency])
	}
	const replaceFn2 = (match: any, key: any) => {
		const item = regionData[String(key).trim()]
		if (!item) {
			console.warn(`未知插值字段: "${key}"; 不存在于 regionData`)
			// 未知字段，保持原样
			return match
		}
		const format = formatFn[item.type]
		if (typeof format !== 'function') {
			console.warn(`匹配字段 "${key}" 的格式化方法不存在! 或不是函数类型: ${typeof format}`)
			// 未知字段，保持原样
			return match
		}
		if (item.type === RegionFormatType.amount.id) {
			const currencySymbol: any = Object.values(AccountRegion).find(
				(i: any) => i.currency === currency
			)?.currencySymbol
			return format(item[currency], { currency, currencySymbol, useName: true })
		}
		if (item.type === RegionFormatType.amountUSD.id) {
			const currencySymbol = AccountRegion.un.currencySymbol
			return format(item[currency], {
				currency: 'USD',
				currencySymbol,
				useName: true
			})
		}
		return format(item[currency])
	}
	return text.replace(regx2, replaceFn2).replace(regx, replaceFn)
}

const search = async () => {
	try {
		loading.value = true
		const { data } = await getMultiText({
			type: route.params.id
		})
		activityInfo.value = JSON.parse(data.data)
	} catch (error) {
	} finally {
		loading.value = false
	}
}

watch(
	() => route.params.id,
	() => {
		search()
	}
)

search()
</script>

<style lang="scss" scoped>
.activity-5x6 {
	//padding: 0 0 calc($home-tabs-height + constant(safe-area-inset-bottom));
	//padding: 0 0 calc($home-tabs-height + env(safe-area-inset-bottom));
	height: 100%;
	&__body {
		height: 100%;
		padding: 30px 18px 70px;
		overflow: auto;
	}
	&__title {
		font-size: 24px;
		line-height: 34px;
		//@include font-bold();
	}
	&__img {
		width: 100%;
		margin-top: 20px;
	}
	&__content {
		margin-top: 20px;
		line-height: 50px;
	}
	&__footer {
		//position: fixed;
		width: fit-content;
		margin: 0 auto;
		//left: 0;
		//right: 0;
		//bottom: calc($home-tabs-height + constant(safe-area-inset-bottom));
		//bottom: calc($home-tabs-height + env(safe-area-inset-bottom));
		height: 60px;
		padding: 0 30px;
		//background: var(--color-bg-6);
		backdrop-filter: blur(2px);
		-webkit-backdrop-filter: blur(2px);
		box-shadow: 0 0 5px rgba(96, 96, 96, 0.1);
		//@include flex-center();
	}
}
</style>

<style lang="scss">
.activity-5x6 {
	img {
		border-radius: 8px !important;
	}
}
</style>
